package com.zx.flow.core.execute.eventhandler;


import com.zx.flow.api.config.FlowConfig;
import com.zx.flow.api.config.FlowConfigNode;
import com.zx.flow.api.dict.FlowDict.Event;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.model.FlowNode;
import com.zx.flow.api.execute.request.FlowParamNodeFinish;
import com.zx.flow.api.execute.response.FlowResult;
import com.zx.flow.api.util.FlowDataUtil;
import com.zx.flow.core.execute.EventHandler;

/**
 * 事件处理器【流程->节点完成】
 */
public class EventFlowNodeFinishHandler extends EventHandler<FlowParamNodeFinish> {

    @Override
    public boolean in(FlowContext flow, FlowParamNodeFinish param) {
        return flow != null;
    }

    @Override
    public FlowResult on(FlowContext flow, FlowParamNodeFinish param) {
        // 流程配置
        FlowConfig config = this.getFlowConfig(flow.getFlowConfigCode(), flow.getFlowConfigId());
        // 下一个节点的配置
        FlowConfigNode toNodeConfig = config.getNode(param.getToNodeCode());
        // 当前节点
        FlowNode currentNode = this.getNode(param.getId(), param.getNodeId());
        // 结束节点
        FlowDataUtil.nodeFinish(currentNode, param.getEvent(), toNodeConfig, param.getRemark(), param.getAccountCode());
        // 保存流程数据
        this.saveNode(flow.getId(), currentNode);
        this.saveFlow(flow);

        // 触发监听
        this.listener(currentNode, Event.nodeFinish);
        return FlowResult.ok(flow);
    }
}
